package com.whut.whw.search;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.whut.whw.R;
import com.whut.whw.base.BaseFragment;
import com.whut.whw.find.GoodsEntity;
import com.whut.whw.find.MyGoodsListAdapter;
import com.whut.whw.util.LogUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 *     author : 杨丽金
 *     time   : 2017/06/27
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class SearchTabFragment extends BaseFragment {
    private static String TITLE = "title";
    private RecyclerView mRvSearchResult;
    private final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
    // 显示查询结果的RecycleView的适配器
    private MyGoodsListAdapter adapter;
    // 查询结果数据集
    private List<GoodsEntity> goodsList = new ArrayList<>();
    // 是否正在上拉加载数据
    private boolean isLoading = false;
    private static final String TAG = "SearchTabFragment";
    private String mTitle = "Defaut Value";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mTitle = getArguments().getString(TITLE);
        }
    }

    @Override
    public View initView(LayoutInflater inflater) {
        View rootView = inflater.inflate(R.layout.fragment_search_result_tab, null);
        mRvSearchResult = (RecyclerView) rootView.findViewById(R.id.rv_search_resultList);
        return rootView;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        initRecycleView();
    }

    /**
     * 初始化recycleView
     */
    private void initRecycleView() {
        // 布局管理器
        mRvSearchResult.setLayoutManager(layoutManager);
        //设置adapter
        adapter = new MyGoodsListAdapter(context, goodsList);
        mRvSearchResult.setAdapter(adapter);
        //设置Item增加、移除动画
        mRvSearchResult.setItemAnimator(new DefaultItemAnimator());

    }

    @Override
    public void setListener() {
        // 下拉加载更多
        mRvSearchResult.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LogUtils.d(TAG, "onScrolled");
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    Log.d("test", "loading executed");
                    if (!isLoading) {
                        isLoading = true;
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                List<GoodsEntity> list = getData();
                                adapter.appendData(list);
                                Log.d("test", "load more completed");
                                isLoading = false;
                            }
                        }, 1000);
                    }
                }
            }
        });
    }

    private List<GoodsEntity> getData() {
        List<GoodsEntity> list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray();
            for (int i = 0; i < 3; i++) {
                JSONObject obj = new JSONObject();

                obj.put("headImg", "http://f.hiphotos.baidu.com/image/pic/item/09fa513d269759ee50f1971ab6fb43166c22dfba.jpg");

                obj.put("mainImgUrl", "http://f.hiphotos.baidu.com/image/pic/item/09fa513d269759ee50f1971ab6fb43166c22dfba.jpg");
                obj.put("name", "包美丽Y下拉加载" + i);
                obj.put("address", "河北张家口" + i);
                obj.put("publishTime", "2017-06-1" + i);
                obj.put("price", "¥20");
                obj.put("title", "书籍便宜专卖啦啦啦");
                obj.put("description", "“淘气”就是那闹事的猫。它在东皇城根穷人家里，原叫做‘小黑’。李太太嫌‘小 \n" +
                        "黑’的称谓太俗，又笑说：“那跟门房‘老白’不成了一对儿么？老白听了要生气的”。猫 \n" +
                        "送到城南长街李家那天，李太太正在请朋友们茶会，来客都想给它起个好听的名字。一个爱 \n" +
                        "慕李太太的诗人说“：在西洋文艺复兴的时候，标准美人都要生得黑，我们读莎士比亚和法 \n" +
                        "国七星派诗人的十四行诗，就知道使他们颠倒的都是些黑美人。");
                obj.put("commentCount", 100 + 10 * i);
                obj.put("likeCount", 230);
                obj.put("wantCount", 8532);
                array.put(obj);
            }
            LogUtils.d(TAG, array.toString());
            Gson gson = new Gson();
            list = gson.fromJson(array.toString(), new TypeToken<List<GoodsEntity>>() {
            }.getType());
            LogUtils.d(TAG, list.size());
            for (int i = 0; i < list.size(); i++) {
                LogUtils.d(TAG, list.get(i).toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
        return list;
    }

    public void refreshData(List<GoodsEntity> list) {
        adapter.updateData(list);
    }

    public static SearchTabFragment newInstance(String title) {
        SearchTabFragment tabFragment = new SearchTabFragment();
        Bundle bundle = new Bundle();
        bundle.putString(TITLE, title);
        tabFragment.setArguments(bundle);
        return tabFragment;
    }
}
